/**
 * Created by alice on 2017/5/04 0001
 */
;-function (window) {
    "use strict";
    //TODO 预设变量写这里，全局变量写在base.js 里面 使用 r. 调用
    var ready = {
        layer: null,
        param_secretary: null,
        start: null,
        end: null,
        case_type: null,
        _user: null,
        param_judge: null,
        param_judge_name: null,
        courtrooms: [],
        courtrooms_name: [],
        page_size: 12,
        dept: [],
        dept_name: [],
        now_judge: [],
        now_judge_name: [],
        judge: [],
        judge_name: [],
        secretary: [],
        secretary_name: [],
        now_secretary: [],
        now_secretary_name: [],
        page_index: 1
    };
    //TODO 初始化的方法写这里面
    var init = function () {
        $('#loading').hide();
        init_ready();//加载预设变量
        $('#startTime').datetimepicker({
            bootcssVer: 3,
            minView: "month", //选择日期后，不会再跳转去选择时分秒
            weekStart: "1",
            format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
            language: 'zh-CN', //汉化
            autoclose: true //选择日期后自动关闭
        }).on('changeDate', function (ev) {
            // console.log(ev.date.valueOf());
        });
        var end_time = $('#endTime');
        $('#endTime').datetimepicker({
            bootcssVer: 3,
            minView: "month", //选择日期后，不会再跳转去选择时分秒
            weekStart: "1",
            format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
            language: 'zh-CN', //汉化
            autoclose: true //选择日期后自动关闭
        }).on('changeDate', function (ev) {
            // console.log(ev.date.valueOf());
        });
        console.info(ready.judge, ready.secretary, ready.dept);
        init_event();
        function init_event() {//TODO 初始化页面事件
            if (ready.start) {
                $("#startTime").find("input").val(ready.start);
            }
            if (ready.end) {
                end_time.find("input").val(ready.end);
            } else {
                end_time.find("input").val(utils.get_url_param(0));
            }

            //点击查询按钮
            $("#conditionBtn").click(function () {
                $("#loading").show();
                Class.count_case_review();
            });
            //部门信息
            Class.select_all_group();
            //法官和法庭信息
            Class.select_all_judges();

            $('#loading').hide();
        }

        function init_ready() {//TODO 初始化预设值
            layui.use('layer', function () {
                ready.layer = layui.layer;
            });
            ready.city = r.user_court_uid;
            var judge_id = utils.get_url_param("judge");
            judge_id ? ready.param_judge = judge_id : '';
            ready.param_secretary = utils.get_url_param("secretary");
            ready.start = utils.get_url_param("start");
            ready.end = utils.get_url_param("end");
            ready.case_type = utils.get_url_param("caseType");
            if (deptAndPost) {
                $.each(deptAndPost, function (n, dept) {
                    if (dept.deptId && ready.dept.indexOf(dept.deptId) < 0) {
                        ready.dept.push(dept.deptId);
                        ready.dept_name.push(dept.deptName);
                    }
                    if (ready.judge.indexOf(dept.userUid) < 0 && "法官" == dept.postName) {
                        ready.judge.push(dept.userUid);
                        ready.judge_name.push(dept.userName);
                    }
                    if (ready.secretary.indexOf(dept.userUid) < 0 && "书记员" == dept.postName) {
                        ready.secretary.push(dept.userUid);
                        ready.secretary_name.push(dept.userName);
                    }
                });
            }

        }
    };
    //TODO 内部调用的方法写这里
    var Class = {
        select_all_group: function () {
            $('#loading').hide();
            var dropmenu_dept = $('#dropmenu_dept').empty();
            dropmenu_dept.append('<option value="" selected>所有部门</option>');
            if (deptAndPost) {
                $.each(ready.dept, function (index, dept) {
                    dropmenu_dept.append('<option value="' + dept + '" >' + ready.dept_name[index] + '</option>');
                    // dropmenu_dept.append('<li><a href="javascript:;" onclick="p.dept_change(\'' + dept.uid + '\')">' + dept.deptname + '</a></li>');
                })
            }
        },
        select_all_judges: function () {
            if (deptAndPost) {
                ready.init_data = deptAndPost

                var dropmenu_judge = $('#allJudges').empty();
                dropmenu_judge.append('<option value="" selected>所有法官</option>');
                var dropmenu_courtroom = $('#allCourtRooms').empty();
                dropmenu_courtroom.append('<option value="" selected>所有法庭</option>');
                var dropmenu_secretary = $("#allSecretary").empty();
                dropmenu_secretary.append('<option value="" selected>所有书记员</option>');
                //法官
                if (ready.param_judge) {
                    if (ready.judge.indexOf(ready.param_judge) > -1) {
                        ready.now_judge.push(ready.param_judge);
                        $.each(deptAndPost, function (judge_no, judge) {
                            if (judge.userUid == ready.param_judge && judge.postName == "法官") {
                                dropmenu_judge.empty();
                                dropmenu_judge.append('<option value="' + judge.userUid + '" >' + judge.userName + '</option>');
                                $(".active").find("span").append("&nbsp;" + judge.userName + "审理过的案件");//今日开庭和排期
                                ready.param_judge_name = judge.userName;
                                ready.now_judge_name.push(judge.userName);
                            }
                        });
                    } else {
                        alert("此法官不属于任何部门！");
                        $.each(deptAndPost, function (index, dept) {
                            if (dept.userUid && dept.postName == "法官") {
                                if (ready.now_judge.indexOf(dept.userUid) < 0) {
                                    ready.now_judge.push(dept.userUid);
                                    ready.now_judge_name.push(dept.userName);
                                    dropmenu_judge.append('<option value="' + dept.userUid + '" >' + dept.userName + '</option>');
                                }
                            }
                        });
                    }

                } else {
                    $.each(deptAndPost, function (index, dept) {
                        if (dept.userUid && dept.postName == "法官") {
                            if (ready.now_judge.indexOf(dept.userUid) < 0) {
                                ready.now_judge.push(dept.userUid);
                                ready.now_judge_name.push(dept.userName);
                                dropmenu_judge.append('<option value="' + dept.userUid + '" >' + dept.userName + '</option>');
                            }
                        }
                    });
                }
                //书记员
                if (ready.param_secretary) {
                    if (ready.secretary.indexOf(ready.param_secretary) > -1) {
                        ready.now_secretary.push(ready.param_secretary);
                        $.each(deptAndPost, function (dept_no, dept) {
                            if (dept.userUid == ready.param_secretary && dept.postName == "书记员") {
                                dropmenu_secretary.empty();
                                dropmenu_secretary.append('<option value="' + dept.userUid + '" >' + dept.userName + '</option>');
                                $(".active").find("span").append("&nbsp;" + dept.userName + "审理过的案件");//今日开庭和排期
                                ready.now_secretary_name.push(dept.userName);
                            }
                        });
                    } else {
                        alert("本书记员不属于任何部门！");
                        $.each(ready.secretary, function (no, secretary) {
                            dropmenu_secretary.append("<option value='" + secretary + "'>" + ready.secretary_name[no] + "</option>");
                        });
                    }

                } else {
                    $.each(ready.secretary, function (no, secretary) {
                        dropmenu_secretary.append("<option value='" + secretary + "'>" + ready.secretary_name[no] + "</option>");
                    });
                }

                if (courtroomList) {
                    $.each(courtroomList, function (index, courtroom) {
                        dropmenu_courtroom.append('<option value="' + courtroom.uid + '" >' + courtroom.name + '</option>');
                        ready.courtrooms.push(courtroom.uid);
                        ready.courtrooms_name.push(courtroom.name);
                    })
                } else {
                    $('#allCourtRooms').html('无法庭');
                }
                Class.select_case_type();
                //加载数据
                Class.count_case_review();

            }
        },
        dept_change: function (dept_uid) {
            ready.now_judge = [];
            ready.now_judge_name = [];
            var dropmenu_judge = $('#allJudges').empty();
            dropmenu_judge.append('<option value="" selected>所有法官</option>');
            var dropmenu_secretary = $("#allSecretary").empty();
            dropmenu_secretary.append('<option value="" selected>所有书记员</option>');
            // dropmenu_judge.append('<li><a href="javascript:;" onclick="p.judge_change(\'sometimes_everything_is_ok\')">所有法官</a></li>');
            // $('#dropmenu_judge').find('a').eq(0).html('所有法官 <span class="caret"></span>');
            if (dept_uid == '') {
                //法官的下拉框
                $.each(ready.dept, function (index, dept) {
                    dropmenu_dept.append('<option value="' + dept + '" >' + ready.dept_name[index] + '</option>');
                    // dropmenu_judge.append('<li><a href="javascript:;" onclick="p.judge_change(\'' + dept.userId + '\')">' + dept.username + '</a></li>');
                    ready.now_judge.push(dept.judge);
                    ready.now_judge_name.push(dept.judge_name);
                });
                //书记员下拉框
                $.each(ready.secretary, function (index, secretary) {
                    dropmenu_secretary.append('<option value="' + secretary + '" >' + ready.secretary_name[index] + '</option>');
                })

            } else {
                // var dept_no = ready.dept.indexOf(dept_uid);
                // $('#dropmenu_dept').find('a').eq(0).html(ready.dept_name[dept_no] + ' <span class="caret"></span>');
                //法官的下拉框
                $.each(deptAndPost, function (index, dept) {
                    if (dept.deptId == dept_uid && dept.postName == "法官") {
                        dropmenu_judge.append('<option value="' + dept.userUid + '" >' + dept.userName + '</option>');
                    }

                });
                //书记员下拉框
                $.each(deptAndPost, function (index, dept) {
                    if (dept.deptId == dept_uid && dept.postName == "书记员") {
                        dropmenu_secretary.append('<option value="' + dept.userUid + '" >' + dept.userName + '</option>');
                    }
                });
            }
        },
        select_case_type: function () {
            if (caseTypeList) {
                var case_type = $("#caseTypeName").empty();
                case_type.append("<option value=''>" + "所有类型" + "</option>");
                $.each(caseTypeList, function (i, valueOfElement) {
                    case_type.append("<option value='" + valueOfElement.uid + "'>" + valueOfElement.name + "</option>");
                });
            }
        },
        // select_secretary: function () {
        //     var select_secretary = $("#allSecretary").empty();
        //     if (ready.secretary) {
        //         $.get(r.base_path + "trial/selectAllSecretaries", {
        //             courtId: ready.city,
        //             id: ready.secretary
        //         }, function (result) {
        //             if (result.data) {
        //                 //console.log(result);
        //                 var select_secretary = $("#allSecretary").empty();
        //                 if (ready.secretary) {
        //                     select_secretary.append("<option value='" + result.data[0].uid + "' selected>" + result.data[0].username + "</option>");
        //                     select_secretary.find("input").val(result.data[0].uid);
        //                     $(".active").find("span").append("&nbsp;" + result.data[0].username + "审理过的案件");//今日开庭和排期
        //                 } else {
        //                     select_secretary.append("<option value=''>" + "所有书记员" + "</option>");
        //                     $.each(result.data, function (i, valueOfElement) {
        //                         select_secretary.append("<option value='" + valueOfElement.uid + "'>" + valueOfElement.username + "</option>");
        //                     });
        //                 }
        //             }
        //         }, 'json');
        //     } else {
        //         $.get(r.base_path + "trial/selectAllSecretaries", {
        //             courtId: ready.city,
        //             id: ready.secretary
        //         }, function (result) {
        //             if (result.data) {
        //                 select_secretary.append("<option value=''>" + "所有书记员" + "</option>");
        //                 $.each(result.data, function (i, valueOfElement) {
        //                     select_secretary.append("<option value='" + valueOfElement.uid + "'>" + valueOfElement.username + "</option>");
        //                 });
        //             }
        //         }, 'json');
        //     }
        // },
        count_case_review: function (pageIndex) {
            if (!pageIndex) {
                pageIndex = 1;
            }
            ready.page_index = pageIndex;
            var caseno = $("#caseno").val();
            var caseName = $("#caseName").val();
            var caseTypeName = $("#caseTypeName").val();
            var courtRoom = $("#allCourtRooms").val();
            // var deptId = $("#dropmenu_dept").val();
            var judgeIds = [];
            if ($("#allJudges option:selected").val() == '' && $("#dropmenu_dept option:selected").val() == '') {

            } else if ($("#allJudges option:selected").val() == '') {
                $("#allJudges option").each(function () {  //遍历所有option
                    var judgeId = $(this).val();   //获取option值
                    if (judgeId != '') {
                        judgeIds.push(judgeId);  //添加到数组中
                    }
                });
            } else {
                judgeIds.push($("#allJudges option:selected").val());
            }
            var secretarys = [];
            if ($("#allSecretary option:selected").val() == '' && $("#dropmenu_dept option:selected").val() == '') {

            } else if ($("#allSecretary option:selected").val() == '') {
                // $("#allSecretary option").each(function () {  //遍历所有option
                //     var st = $(this).val();   //获取option值
                //     if (st != '') {
                //         secretarys.push(st);  //添加到数组中
                //     }
                // });
            } else {
                secretarys.push($("#allSecretary option:selected").val());
            }
            // var secretary = ready.secretary||$("#allSecretary").val();
            var startTime = $("#startTime").find("input").val();
            var endTime = $("#endTime").find("input").val();
            // console.log(caseName, caseTypeName, courtRoom, judge, secretary, startTime, endTime);
            var row_no_padding = $(".row-no-padding").empty();
            $.ajax({
                url: r.base_path + "judge/selectMoreCasePlanOrReview",
                type: "get",
                dataType: "json",
                data: {
                    courtUid: r.user_court_uid,
                    archives: caseno,
                    caseName: caseName,
                    type: caseTypeName,
                    courtRoom: courtRoom,
                    judgeList: judgeIds.toString(),
                    // secretaryList: secretarys.toString(),
                    secretaryId: secretarys[0],
                    startDate: startTime,
                    endDate: endTime,
                    status: 0,
                    review: 1,
                    page: pageIndex,
                    pageSize: ready.page_size
                },
                success: function (result) {
                    // console.log(result.data);
                    var s = result.data.count;
                    if (s == 0) {
                        Class.page(1, 1, null);
                    } else {
                        Class.page(pageIndex, Math.ceil(s / 12), Class.count_case_review);
                    }

                    if (result.code == 0) {
                        if (result.data.count <= 0) {
                            row_no_padding.append('<span>暂无开庭信息</span>');
                        } else {
                            var picNum = 6;
                            $.each(result.data.data, function (i, valueOfElement) {

                                var caseName = valueOfElement.name;
                                var startDate = valueOfElement.startDate;
                                var status = valueOfElement.status;
                                var courtroom_name = valueOfElement.courtroomName;
                                var statusName = "";
                                if (0 == status) {
                                    statusName = "排期";
                                } else if (1 == status || 5 == status) {
                                    statusName = "开庭";
                                } else if (2 == status) {
                                    statusName = "休庭";
                                } else if (3 == status) {
                                    statusName = "闭庭";
                                } else {
                                    statusName = "归档";
                                }
                                var success = false;
                                if (favorites&&$.inArray(valueOfElement.planUid,favorites)>-1){
                                    success = true;
                                }
                                var randomNum = parseInt(picNum * Math.random() + 1);//随机出1到picNum的整数
                                var href = r.base_path + "archives/play?planUid=" + valueOfElement.planUid;
                                var html = '<div class="col-md-2 col-xs-6">' +
                                    '<div class="more-reviewing-item">' +
                                    '<a href="' + href + '">' +
                                    '<div class="more-reviewing-item-img-panel">' +
                                    '<p class="more-reviewing-item-img-panel-top">' + (courtroom_name ? courtroom_name : '未知') + '</p>' +
                                    '<img src="' + r.base_path + "assets/img/more_court_test" + randomNum + ".jpg" + '" alt="法院">' +
                                    '<p class="more-reviewing-item-img-panel-bottom" >' + statusName + '</p>' +
                                    '</div>' +
                                    '<p id="startDate">' + startDate + '</p>' +
                                    '<p id="caseNoDis">' + (valueOfElement.archives ? valueOfElement.archives : '未知') + '</p>' +
                                    '<p class="more-reviewing-item-depiction">' +
                                    '<i class="fa fa-thumb-tack ' + (success ? 'status-top' : '') + '" title=收藏 id="' + valueOfElement.planUid + '..' + r.user_court_uid + '"></i>' +
                                    '<span>' + (caseName ? caseName : "&nbsp;") + '</span>' +
                                    '</p>' +
                                    '</a>' +
                                    '</div>' +
                                    '</div>';
                                row_no_padding.append(html);
                            });
                            $(".fa-thumb-tack").click(function (e) {
                                e.preventDefault();
                                var cid = this.id.split('..');
                                var uid = cid[0];
                                var class_name = '' + this.className;
                                layui.use(['layer', 'form'], function () {
                                    var layer = layui.layer;
                                    if (class_name.indexOf("status-top") < 0) {
                                        layer.confirm('确定收藏吗？', {
                                            btn: ['是的', '取消'] //按钮
                                        }, function () {
                                            $.post(r.base_path + "favorite/like", {
                                                planUid: uid
                                            }, function (result) {
                                                favorites.push(uid);
                                                layer.msg(result.message);
                                                Class.count_case_review(ready.page_index);
                                            }, 'json')
                                        }, function () {

                                        });
                                    } else {
                                        layer.confirm('确定取消收藏吗？', {
                                            btn: ['是的', '取消'] //按钮
                                        }, function () {
                                            $.post(r.base_path + "favorite/unlike", {
                                                planUid: uid
                                            }, function (result) {
                                                var index = favorites.indexOf(uid);
                                                if (index > -1) {
                                                    favorites.splice(index, 1);
                                                }
                                                layer.msg(result.message);
                                                Class.count_case_review(ready.page_index);
                                            }, 'json')
                                        }, function () {

                                        });
                                    }
                                });
                            });
                        }
                        $("#loading").hide();
                        row_no_padding.show();
                    } else {
                        $("#loading").hide();
                        row_no_padding.append('<span>' + result.msg + '</span>');
                    }
                }
            }).fail(function () {
                $('#loading').hide();
            });
        },
        page: function (now, totalPages, callback) {
            base.pagination('#_page', {
                currentPage: now,
                totalPages: totalPages,
                onPageClicked: function (page) {
                    callback(page);
                }
            });
        }
    };
    init();
    //TODO 对外公开的方法写在这里
    window.p = {
        get_sum_case: Class.count_case_review,
        dept_change: Class.dept_change
    };
}(window);
